package com.googlecode.yoohoo.utils;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;

public class OsgiUtils {

	public static String getSymbolicName(Bundle bundle) {
		String symbolicName = bundle.getSymbolicName();
		if (symbolicName == null) {
			symbolicName = "no.symbolic.name.bundle";
		}
		
		return symbolicName;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getServiceInstance(BundleContext context, Class<T> clazz, String name) {
		ServiceReference[] references = null;
		try {
			references = context.getServiceReferences(clazz.getName(), FilterCreator.equal(
							Constants.KEY_SERVICE_INSTANCE_NAME, name));
		} catch (InvalidSyntaxException e) {
			throw new RuntimeException("Invalid filter.", e);
		}
		
		if (references == null || references.length == 0) {
			return null;
		}
		
		return (T)context.getService(references[0]);
	}
	
	public static Bundle getBundle(BundleContext bundleContext, String bundleSymblicName) {
		for (Bundle bundle : bundleContext.getBundles()) {
			if (bundle.getSymbolicName().equals(bundleSymblicName)) {
				return bundle;
			}
		}
		
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getService(BundleContext bundleContext, Class<T> clazz) {
		ServiceReference reference = bundleContext.getServiceReference(clazz.getName());
		if (reference == null)
			return null;
		
		return (T)bundleContext.getService(reference);
	}
}
